package initdb

import (
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gitee.com/zaiqiang231/lovesport-user-service/app/store"
)

func RegisterInit() {

	store.RegisterInit(initPolicy{})
	store.RegisterInit(initSysBaseMenu{})
	store.RegisterInit(initSysBaseMenuParameter{})
	store.RegisterInit(initSysAuthority{})
	store.RegisterInit(initSysApi{})
	store.RegisterInit(initUser{})
	store.RegisterInit(initSysOperationRecord{})
	store.RegisterInit(initSysDictionaryDetail{})
	store.RegisterInit(initSysDictionary{})

	store.GetDataStore().CreateTables()

	runTest := false

	if !runTest {
		return
	}
	//test
	err := store.GetDataStore().DB.AutoMigrate(&model.TestArticle{}, &model.TestTAG{})
	if err != nil {
		baseLog.Errorf("test 创建失败 %v", err)
	}
	tag1 := model.TestTAG{TagId: "001", TagName: "React 5"}

	err = store.GetDataStore().DB.Save(&tag1).Error
	if err != nil {
		baseLog.Errorf("tag1 Save失败 %v", err)
	}

	tags1 := model.TestTAG{TagId: "111", TagName: "React 111"}
	tags2 := model.TestTAG{TagId: "222", TagName: "React 222"}
	article := model.TestArticle{
		Title:   "Redux进阶教程",
		Content: "正文内容",
		TagId:   "art1",
		Tag:     tag1,
		// 子项中的数据必须是保存过或者查找出的数据（即数据库已有的数据）
		Tags: []model.TestTAG{
			tags1,
			tags2,
		},
	}
	err = store.GetDataStore().DB.Save(&article).Error
	if err != nil {
		baseLog.Errorf("article Save失败 %v", err)
	}
	result := model.TestArticle{}
	err = store.GetDataStore().DB.Where("title = ?", "Redux进阶教程").Preload("Tag").Preload("Tags").Find(&result).Error
	if err != nil {
		baseLog.Errorf("article Find失败 %v", err)
	} else {
		baseLog.Errorf("article Find %v", result)
	}

	tagsUpdate := []model.TestTAG{
		model.TestTAG{TagId: "111 u", TagName: "React 111 u"},
		model.TestTAG{TagId: "222 u", TagName: "React 222 u"},
	}
	err = store.GetDataStore().DB.Model(&result).Association("Tags").Replace(tagsUpdate)
	if err != nil {
		baseLog.Errorf("article Save失败 %v", err)
	}
	result2 := model.TestArticle{}
	err = store.GetDataStore().DB.Where("title = ?", "Redux进阶教程").Preload("Tag").Preload("Tags").Find(&result2).Error
	if err != nil {
		baseLog.Errorf("result2 article Find失败 %v", err)
	} else {
		baseLog.Errorf("result2 article Find %v", result2)
	}

}
